######################################
#                                    #
#  AutoArchiveManager - By Yingest   #
#                                    #
# The Core py for Convert Bin files  #
#                                    #
######################################

from PIL import Image
import numpy as np
import cv2
import os


def convert_bin_to_bmp(filePath, type: str = '.png'):
    if not type.lower() in ['.bmp', '.jpg', '.jpeg', '.png']: return -1
    sizeTemp = [[1920, 1536], [3840, 2160]]
    relsize = os.path.getsize(filePath)
    for size in sizeTemp:
        if relsize == size[0] * size[1] * 2:
            width = size[0]
            height = size[1]

    try:
        with open(filePath, mode='rb') as file:
            pixel_array = np.fromfile(file, dtype=">u2", count=width * height)
        min_val = np.min(pixel_array)
        max_val = np.max(pixel_array)
        normalized_array = ((pixel_array - min_val) / (max_val - min_val) *
                            255).astype(np.uint8)
        # Adjust the array size to match the image dimensions
        normalized_array = normalized_array.reshape((height, width))
        rgb_image = cv2.cvtColor(normalized_array.astype(np.uint8),
                                 cv2.COLOR_BayerGB2RGB)
        pil_image = Image.fromarray(rgb_image)
        targetpath = filePath.replace('.bin', type)
        pil_image.save(targetpath)
    except Exception as e:
        print(f"Error: {e}")
        return -2
    return 0


if __name__ == "__main__":
    # Replace 'raw_folder' with the actual path to your RAW images
    file_Path = r'C:\Users\tding1\Downloads\RawImages\C654100C30000243_6p10ms_RelativeIllumination_D50_8_29_2024_20_41_03_548.bin'

    # Call the main conversion function
    convert_bin_to_bmp(file_Path)
